package com.itheima.reggie.common;

import com.itheima.reggie.controller.EmployeeController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
//@ControllerAdvice//指定拦截那些类型的控制器
//@ResponseBody//将方法的返回值R对象转换为json数据,响应给页面
@RestControllerAdvice(annotations = {Controller.class,RestController.class})//指定拦截的controller方法
@Slf4j
//全局异常处理
public class GlobalExceptionHandler {
    //异常处理
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //打印异常信息
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已经存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    //异常处理
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        //打印异常信息
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
